<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>欢迎页面-X-admin2.0</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="shortcut icon" href="__STATIC__/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="__STATIC__/css/font.css">
    <link rel="stylesheet" href="__STATIC__/css/xadmin.css">
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
    <script type="text/javascript" src="__STATIC__/lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="__STATIC__/js/xadmin.js"></script>
    <script type="text/javascript" src="__STATIC__/lib/UEditor/ueditor.config.js"></script>
    <script type="text/javascript" src="__STATIC__/lib/UEditor/ueditor.all.js"></script>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        .images{
            width: 100px;
            height: 100px;
            margin-left: 10px;
            margin-bottom: 5px;
        }
        #demo2{width: 100%;overflow: hidden;}
        #demo2>div{float: left;margin-right: 15px}
        .spec-cv{width: 24%;float: left;margin-top: 10px;}
    </style>
</head>

<body>
<div class="x-body">
    <form class="layui-form">
        <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
            <ul class="layui-tab-title">
                <li class="layui-this">基本</li>
                <li>图片</li>
                <li>规格</li>
                <li>详情</li>
            </ul>
            <div class="layui-tab-content" >
                <div class="layui-tab-item layui-show" style="margin-top: 30px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            商品名称
                        </label>
                        <div class="layui-input-inline">
                            <input type="text" name="good_name" required="" lay-verify="required"
                                   autocomplete="off" class="layui-input" value="">
                        </div>
                        <div class="layui-form-mid layui-word-aux">
                            <span class="x-red">*</span>商品完整名称
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            商品短标题
                        </label>
                        <div class="layui-input-inline">
                            <input type="text" name="good_title" required="" lay-verify="required"
                                   autocomplete="off" class="layui-input" value="">
                        </div>
                        <div class="layui-form-mid layui-word-aux">
                            <span class="x-red">*</span>用于快递的标题
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            关键字
                        </label>
                        <div class="layui-input-inline">
                            <input type="text" name="good_title" required="" lay-verify="required"
                                   autocomplete="off" class="layui-input" value="">
                        </div>
                        <div class="layui-form-mid layui-word-aux">
                            <span class="x-red">*</span>用于搜索的关键字
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            所属分类
                        </label>
                        <div class="layui-input-inline" style="width: 100px;">
                            <select name="category" lay-verify="required">
                                <option value=""></option>
                                {volist name="data" id="vo"}
                                <option value="{$vo.id}">{$vo.category_name}</option>
                                {/volist}
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 100px;">
                            <select name="category_id" lay-verify="required">
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label  class="layui-form-label">
                            单价
                        </label>
                        <div class="layui-input-inline" style="width: 80px;">
                            <input type="number" name="price" required="" value="" lay-verify="required"
                                   autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-form-mid layui-word-aux">
                            <span class="x-red">*</span>商品价格
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label  class="layui-form-label">
                            单位
                        </label>
                        <div class="layui-input-inline" style="width: 80px;">
                            <input type="text" name="price" required="" value="件" lay-verify="required"
                                   autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-form-mid layui-word-aux">
                            <span class="x-red">*</span>商品单位,默认:件
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            库存
                        </label>
                        <div class="layui-input-inline" style="width: 80px;">
                            <input type="number" name="stock" required="" value="" lay-verify="required"
                                   autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-form-mid layui-word-aux">
                            <span class="x-red">*</span>商品库存
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            排序
                        </label>
                        <div class="layui-input-inline" style="width: 80px;">
                            <input type="number" name="sort" required="" value="0"
                                   autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-form-mid layui-word-aux">
                            <span class="x-red">*</span>决定商品排列顺序,数字越大越靠前。
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            状态
                        </label>
                        <div class="layui-input-block">
                            <input type="radio" name="status" lay-skin="primary" value="1" title="上架" checked>
                            <input type="radio" name="status" lay-skin="primary" value="0" title="下架">
                        </div>
                    </div>
                </div>
                <div class="layui-tab-item" style="margin-top: 30px;">
                    <div class="layui-upload">
                        <button type="button" class="layui-btn" id="test1">LOGO上传</button>
                        <div class="layui-upload-list">
                            <img class="layui-upload-img" id="demo1">
                            <input type="hidden" name="image" value="" id="image">
                            <p id="demoText"></p>
                        </div>
                    </div>
                    <div class="layui-upload">
                        <button type="button" class="layui-btn" id="test2">轮播图片上传</button>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览图：
                            <div class="layui-upload-list" id="demo2"></div>
                        </blockquote>
                    </div>
                </div>
                <div class="layui-tab-item" style="margin-top: 10px;" id="specDome">
                    <a href="javascript:;" class="layui-btn layui-btn-sm" style="margin-left: 0;" id="specAdd"><i class="layui-icon layui-icon-add-1"></i>添加规格</a>
                    <a href="javascript:;" class="layui-btn layui-btn-sm" style="margin-left: 0;" id="specRefresh"><i class="layui-icon layui-icon-refresh"></i>刷新规格项目表</a>
                    <table class="layui-table" id="skuList">
                        <thead>
                        <tr></tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
                <div class="layui-tab-item">
                    <textarea id="container" name="content" type="text/plain"
                    style="width: 800px;height: 300px;margin-left: 10%;"></textarea>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label  class="layui-form-label">
            </label>
            <button  class="layui-btn" lay-filter="add" lay-submit="">
                保存
            </button>
        </div>
    </form>
</div>
<!--<script src="https://cdn.bootcss.com/jquery/3.1.0/jquery.js"></script>-->
<script>

    layui.use(['form','layer','element','upload'], function(){
        var form = layui.form
            ,layer = layui.layer
            ,upload = layui.upload
            ,element = layui.element;

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            ,url: '{:url("Goods/goodsImg")}'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接（base64）
                    $('#demo1').attr('class', 'images'); //图片链接（base64）
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code != 1){
                    return layer.msg('上传失败');
                }
                //上传成功
                $("#image").val(res.url);
                var demoText = $('#demoText');
                demoText.html('<span>上传成功</span><a class="layui-btn layui-btn-xs demo-del">删除</a>');
                demoText.find('.demo-del').on('click', function(){
                    var url = $("#image").val();
                    $.post('{:url("Goods/goodsImgDel")}',{imgUrl:url},function (res) {
                        if (res.code == 1){
                            layer.msg(res.msg,{icon:6,time:1000});
                            $('#demo1').removeAttr('src');
                            $('#demo1').removeAttr('class','images');
                            $("#image").val('');
                            $("#demoText").children().remove();
                        } else {
                            layer.msg(res.msg,{icon:5,time:1000});
                        }
                    });
                });
                form.render();
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span><a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });
        //多图片上传
        upload.render({
            elem: '#test2'
            ,url: '{:url("Goods/goodsImg")}'
            ,multiple: true
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    // $('#demo2').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img images">');
                });
            }
            ,done: function(res){
                //上传完毕
                var str = '<div><div class="uploadImages-top"><img src="'+ res.url+'" alt="" class="layui-upload-img images"/></div><div class="uploadImages-bot"><input type="hidden" name="images[]" value="'+ res.url+'"><span>上传成功</span><a class="layui-btn layui-btn-xs demo2-del">删除</a></div></div>';
                $('#demo2').append(str);
                form.render();
            }
        });
        $(document).on('click','.demo2-del',function () {
            console.log($(this).siblings('input').val());
            var url = $(this).siblings('input').val();
            var item = $(this).parent().parent();
            $.post('{:url("Goods/goodsImgDel")}',{imgUrl:url},function (res) {
                if (res.code == 1){
                    layer.msg(res.msg,{icon:6,time:1000});
                    item.remove();
                } else {
                    layer.msg(res.msg,{icon:5,time:1000});
                }
            });
        });
        var ue = UE.getEditor('container');
            ue.addListener("contentChange",function(){
                $("#container").val(ue.getContent());
            });
        var key = 1;
        $(document).on('click','#specAdd',function () {
            var str = '                    <div class="layui-form-item">\n' +
                '                        <div class="layui-form-item">\n' +
                '                            <div class="layui-input-inline" style="width: 60%">\n' +
                '                                <input type="text" name="spec[]" value=""\n' +
                '                                       autocomplete="off" class="layui-input" placeholder="规格名称 (比如：颜色)">\n' +
                '                                <input type="hidden" name="key[]" value="'+ key +'" class="key"> \n' +
                '                            </div>\n' +
                '                            <div style="line-height: 38px;">\n' +
                '                                <a href="javascript:;" class="layui-btn layui-btn-sm spec-add" style="margin-left: 0;">添加规格项</a>\n' +
                '                                <a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-danger spec-del" style="margin-left: 0;">删除</a>\n' +
                '                            </div>\n' +
                '                        </div>\n' +
                '                    </div>';
            $('#specDome #specAdd').before(str);
            key++;
            form.render();
        });
        $(document).on('click','.spec-del',function () {
            $(this).parent().parent().parent().remove();
            form.render();
        });
        $(document).on('click','.spec-add',function () {
            var keys = $(this).parent().siblings('.layui-input-inline').children('input[name="key[]"]').val();
            var str = '                    <div  class="spec-cv">\n' +
                '                        <div class="layui-input-inline">\n' +
                '                            <input type="text" name="values[]" value="" autocomplete="off" class="layui-input">\n' +
                '                            <input type="hidden" name="keys[]" value="'+ keys +'" >\n' +
                '                        </div>\n' +
                '                        <div style="line-height: 38px;">\n' +
                '                            <a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-danger value-del" style="margin-left: 0;">\n' +
                '                                <i class="layui-icon layui-icon-close"></i>\n' +
                '                            </a>\n' +
                '                        </div>\n' +
                '                    </div>';
            $(this).parent().parent().parent().append(str);
            form.render();
        });
        $(document).on('click','.value-del',function () {
            $(this).parent().parent().remove();
            form.render();
        });
        $(document).on('click','#specRefresh',function () {
            var arr=[];
            var arr_value=[];
            var arr_name = [];
            $("#specDome>.layui-form-item").each(function () {
                $(this).find('input[name="values[]"]').each(function () {
                    arr_value.push(this.value);
                });
                arr.push(arr_value);
                arr_value = [];
            });
            $('#specDome').find('input[name="spec[]"]').each(function () {
                arr_name.push(this.value);
            });
            console.log(arr);
            if (arr.length >= 2){
                var ret = descartes(arr);
            }else {
                var ret = descate(arr[0]);
            }
            console.log(ret);
            skuList(ret,arr_name);
            form.render();
        });
        //监听提交
        form.on('submit(add)', function(data){
            console.log(data.field);
            //发异步，把数据提交给php
            // $.post('{:url("Admin/adminAdd")}',data.field,function (res) {
            //     if (res.code == 1){
            //         layer.msg(res.msg, {icon: 6,time:1000},function () {
            //             // 获得frame索引
            //             window.parent.location.reload();
            //             var index = parent.layer.getFrameIndex(window.name);
            //             //关闭当前frame
            //             parent.layer.close(index);
            //         });
            //     }else {
            //         layer.msg(res.msg, {icon: 5,time:1500});
            //     }
            // });
            return false;
        });
    });
    function skuList(sku, skuName) {
        let header = '';
        let content = '';
        skuName.forEach(function (data) {
            header += '<th>' + data + '</th>';
        });
        header+='<th>图片</th><th>售价</th><th>库存</th>';
        for (let i = 0; i <sku.length; i++){
            content += '<tr>';
            let name = sku[i].join(',');
            for (let j = 0; j <sku[i].length; j++){
                content += '<td>' + sku[i][j] + '</td>';
            }
            // content+= '<td><input type="hidden" class="ss_image" name="ss_image[]" value="" /><input name="" class="ss_imgaebutton" type="button" value="选择图片" /></td><td><input type="text" name="ss_original_price[]" value="0"></td><td><input name="ss_current_price[]" type="text" value="0"></td><td><input name="ss_stock[]" type="text" value="0"></td><td><input name="ss_sales_volume[]" type="text" value="0"></td><input name="ss_name[]" type="hidden" value=""/>';
            content += '<td><form enctype="multipart/form-data" ><input type="hidden" class="ss_image" name="ss_image[]"/>' + '<label class="choiceImages"><input type="file" name="file" class="hide">选择图片</label></form></td>\n' +
                '<td><input name="ss_current_price[]" class="layui-input" autocomplete="off" type="text" value=""></td>\n' +
                '<td><input name="ss_stock[]" type="text" class="layui-input" autocomplete="off" value=""></td>\n' +
                '<input name="ss_name[]" type="hidden" value="'+ name +'"/>';
        }
        $("#skuList thead tr").html(header);
        $('#skuList tbody').html(content);
    }
    function descartes(array){
        if( array.length < 2 ) return array || [];
        for (var i=0;i<array.length;i++){
            var leg = array[i].length;
            if (leg == 0){
                array.splice(i, 1);
            }
        }
        return [].reduce.call(array, function(col, set) {
            var res = [];
            col.forEach(function(c) {
                set.forEach(function(s) {
                    var t = [].concat( Array.isArray(c) ? c : [c] );
                    t.push(s);
                    res.push(t);
                })});
            return res;
        });
    }
    function descate(array) {
        var ret = [];
        for (var i=0;i<array.length;i++){
            var arr = array[i];
            var ret2 = [];
            ret2.push(arr);
            ret.push(ret2);
        }
        return ret;
    }
    // 上传图片
    $(document).on('change','.choiceImages',function(){
        let aaa=$(this).parent("form")[0];
        let formData = new FormData(aaa);
        let fileImgVal=$(this).children("input")[0].files[0];
        $.ajax( {
            url:'{:url("Goods/goodsImg")}',
            cache:false,
            type:'post',
            data:formData,
            dataType:'json',
            contentType: false,
            processData: false,//不处理数据
            success:function(data){

                console.log("上传结果:",data);
            },
            error : function() {
                alert("图片上传异常！");
            }
        });
    });
</script>

</body>

</html>